<template>
  <div class="app-container">
    <div class="filter-container" style="margin: 20px 0;">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="12" :lg="16" :xl="16">
          <el-input  clearable class="filter-item" v-model="listQuery[0].value" placeholder="标题" @keyup.enter.native="fetchListData"></el-input>
          <el-input  clearable class="filter-item" v-model="listQuery[1].value" placeholder="作者" @keyup.enter.native="fetchListData"></el-input>
          <el-input  clearable class="filter-item" v-model="listQuery[2].value" placeholder="主图" @keyup.enter.native="fetchListData"></el-input>
          <el-input  clearable class="filter-item" v-model="listQuery[3].value" placeholder="主视频" @keyup.enter.native="fetchListData"></el-input>
          <el-date-picker  clearable class="filter-item-time" v-model="listQuery[5].value" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" @change="fetchListData" type="daterange" range-separator=" - " start-placeholder="创建开始" end-placeholder="创建结束"></el-date-picker>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8" style="text-align: right">
          <el-button  v-waves class="filter-button" icon="el-icon-back" @click="$router.back()">返回</el-button>
          <el-button  v-waves type="primary" class="filter-button" icon="el-icon-search" @click="fetchListData">搜索</el-button>
          <el-button  v-waves type="primary" class="filter-button" icon="el-icon-edit" v-permission="['article:add']" @click="handleCreateArticle">新建</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="table-container">
      <base-list ref="table" url="/news/article/list" :query="listQuery" :columns="columns" :format="format">
        <template slot="actions" slot-scope="scope">
          <el-button  v-waves v-permission="['article:edit']" type="primary" @click="handleEditArticle(scope.$index, scope.row)">编辑</el-button>
          <el-button  v-waves v-permission="['article:delete']" type="danger" @click="handleDeleteArticle(scope.$index, scope.row)">删除</el-button>
        </template>
      </base-list>
      <el-dialog :title="dialogTextMap[dialogStatus]" :visible.sync="createDialogVisible" :width="$store.state.app.device === 'mobile' ? '100%' : '60%'">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-width="auto" label-suffix=": " :inline="false" >
          <el-form-item label="标题" prop="title">
            <el-input  clearable class="form-item" v-model="temp.title" placeholder="标题"></el-input>
          </el-form-item>
          <el-form-item label="作者" prop="author">
            <el-input  clearable class="form-item" v-model="temp.author" placeholder="作者"></el-input>
          </el-form-item>
          <el-form-item label="主图" prop="mainImage">
            <upload-image class="form-item"  :ref="'mainImage'" @uploadSuccess="mediaChange" :fileUrl="temp.mainImage" columnName="mainImage"></upload-image>
          </el-form-item>
          <el-form-item label="主视频" prop="mainVideo">
            <upload-video class="form-item"  :ref="'mainVideo'" @uploadSuccess="mediaChange" :fileUrl="temp.mainVideo" columnName="mainVideo"></upload-video>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <editor-quill columnName="content" :editorContext="temp.content" @textHtmlChange="contentEditChange" placeholder="内容"></editor-quill>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button  v-waves @click="createDialogVisible = false">取消</el-button>
          <el-button  v-waves type="primary" v-permission="['article:add' || 'article:edit ']" @click="dialogStatus==='create'?handleAddArticle():handleUpdateArticle()">提交</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import permission from '@/directive/permission/index.js' // 权限判断指令
import waves from '@/directive/waves' // waves directive
import { create as createArticle, update as updateArticle, deleteById as deleteArticle, updateSate as setArticleState, } from '@/api/news/article'
import { mapGetters } from 'vuex'
import BaseList from '@/components/BaseList'
import UploadVideo from '@/components/UploadVideo'
import UploadImage from '@/components/UploadImage'
import EditorQuill from '@/components/EditorQuill'
export default {
  name: 'Article',
  components: { BaseList, UploadVideo, UploadImage, EditorQuill },
  directives: { permission, waves },
  data() {
    return {
      list: null,
      columns: [
        { key: 'index', label: '编号', width: 40, fixed: 'left' },
        { key: 'title', label: '标题' },
        { key: 'author', label: '作者' },
        { key: 'mainImage', label: '主图' , type:'image' },
        { key: 'mainVideo', label: '主视频' , type:'video' },
        { key: 'content', label: '内容', sortable: true  },
        { key: 'createTime', label: '创建时间',sortable: true },
        { key: 'actions', label: '操作', width: 320, fixed: 'right', align: 'left' }
      ],
      format: {
        index: (data, index) => { return index + 1 },
      },
      listQuery: [
        { column: "title", condition: "like", value: null },
        { column: "author", condition: "like", value: null },
        { column: "mainImage", condition: "like", value: null },
        { column: "mainVideo", condition: "like", value: null },
        { column: "content", condition: "=", value: null },
        { column: "createTime", condition: "bt", value: null }
      ],
      temp: {title: undefined,author: undefined,mainImage: undefined,mainVideo: undefined,content: undefined},
      dialogTextMap: {update: '编辑',create: '新建', detail: '详情'},
      rules: {
        title: [{ required: true, message: '标题必填!', trigger: 'blur' }],
        author: [{ required: true, message: '作者必填!', trigger: 'blur' }],
        mainImage: [{ required: true, message: '主图必填!', trigger: 'blur' }],
        mainVideo: [{ required: true, message: '主视频必填!', trigger: 'blur' }],
        content: [{ required: true, message: '内容必填!', trigger: 'change' }],
      },
      dialogStatus: '',
      createDialogVisible: false,
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    const allOptions = JSON.parse(localStorage.getItem('allOptions'))
  },
  mounted() {
    this.fetchListData()
  },
  methods: {
    fetchListData() {
      this.$refs.table.fetchData(1)
    },
    reloadListData() {
      this.$refs.table.fetchData()
    },
    resetTemp() {
      this.temp = {title: undefined,author: undefined,mainImage: undefined,mainVideo: undefined,content: undefined,}
    },
    mediaChange(val, index, column) {
      this.temp[column] = val;
    },
    handleCreateArticle() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEditArticle(index, val) {
      this.temp = Object.assign({}, val)
      this.dialogStatus = 'update'
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAddArticle() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const queryData = Object.assign({}, this.temp)
          queryData.status = Number(queryData.status)
          createArticle(queryData).then(() => {
            // this.list.unshift(queryData)
            this.fetchListData()
            this.createDialogVisible = false
            this.$notify.success('文章创建成功!')
          })
        }
      })
    },
    handleUpdateArticle() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp)
          updateArticle(tempData).then(() => {
            this.reloadListData()
            this.createDialogVisible = false
            this.$notify.success('文章更新成功!')
          })
        }
      })
    },
    handleDeleteArticle(index, val) {
      const self = this
      this.$confirm('确定要删除该文章？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteArticle(val.id).then(() => {
          self.reloadListData()
          self.$notify.success('文章已删除!')
        })
      }).catch(() => {})
    },
    contentEditChange(val, index, columnName) {
      this.temp[columnName] = val
    }
  }
}
</script>

